package jwt

import (
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/lab-online/pkg/util"
)

// GenToken generates a new JWT token
// 如果 role 为 0，将生成一个过期时间较长的 token 用于刷新 token
func (j *JsonWebToken) GenToken(username string, role uint8) (string, error) {
	now := time.Now()

	claims := &Claims{
		Username: username,
		Role:     role,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    j.config.Issuer,
			IssuedAt:  jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(now.Add(j.config.Expire)),
		},
	}

	claims.RegisteredClaims.ExpiresAt = jwt.NewNumericDate(now.Add(
		util.ConditionalPicker(role == 0, j.config.RefreshExpire, j.config.Expire),
	))

	return jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(j.rsa.PrivateKey)
}
